package com.zxs.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

public class HttpClient {
    private static CloseableHttpClient client = null;
    static {
        try {
            HttpClientBuilder builder = HttpClients.custom();
            SSLContext sc = SSLContextBuilder.create().loadTrustMaterial(new TrustStrategy() {
                // 信任所有
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            builder.setSSLContext(sc);// 忽略证书验证
            builder.evictExpiredConnections();// 自动释放一段时间不活跃的连接，默认10秒
            client = builder.build();// 默认每个主机2个连接，最多20个连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用指定的字符集向指定的URL连接POST数据，延时可指定
     *
     * @param paras
     * @param charset
     * @param timeCout
     * @return
     */
    public static String post(String url, Map<String, String> paras, String charset, int connectTime, int timeCout) {
        String r = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (paras != null) {
                for (Map.Entry<String, String> e : paras.entrySet()) {
                    nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            r = EntityUtils.toString(entity, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 使用指定的字符集向指定的URL连接POST数据，延时可指定
     *
     * @param charset
     * @param timeCout
     * @return
     */
    public static String postJson(String url, String json, String charset, int connectTimeout, int timeCout) {
        String r = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            r = EntityUtils.toString(entity, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }
    public static String postJson(String url, String json) {
        System.out.println(json);
        String r = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            RequestConfig config = RequestConfig.custom().build();
            httpPost.setConfig(config);
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            r = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 使用GET方法向指定的URL传送数据
     *
     * @param urlvalue
     * @return
     */
    public static String get(String urlvalue, Integer connectTimeout, Integer timeCout) {
        String r = "";
        try {
            HttpGet httpGet = new HttpGet(urlvalue);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
            httpGet.setConfig(config);
            CloseableHttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            r = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 使用utf-8字符集向给定的URL连接POST数据，延时是固定的
     *
     * @param urlvalue
     * @param paras
     * @return
     */
    public static String post(String urlvalue, Map<String, String> paras) {
        return post(urlvalue, paras, "utf-8", ClientUtil.CONNECT_TIMEOUT, ClientUtil.SOCKET_TIMEOUT);
    }

    /**
     * 使用utf-8字符集向给定的URL连接POST数据，延时是固定的
     *
     * @param urlvalue
     * @param paras
     * @param charset
     * @return
     */
    public static String post(String urlvalue, Map<String, String> paras, String charset, int timeount) {
        return post(urlvalue, paras, "utf-8", ClientUtil.CONNECT_TIMEOUT, timeount);
    }
}

